layui.use(['layer', 'form', 'jquery', 'table','upload'], function () {
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.jquery;
    var table = layui.table;
    var upload = layui.upload;
    //获取使用人id
    var createId = localStorage.getItem("createId");
    //树
    var settingss = {
        view: {
            dblClickExpand: false,
            addDiyDom: addDiyDom
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "categroyId",
                pIdKey: "parentId",
                rootPId: -1
            },
            key: {
                enable: true,
                name: "title"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            onRightClick: onRightClick,
            beforeRename: beforeRename,
            onClick: chooseNode,
        }
    };
    //加载树
    var zTree, rMenu;
    $(document).ready(function () {
        $.ajax({
            url: "/courseClass/getCourseClass",
            type: 'post',
            dataType: 'json',
            success: function (data) {
                zTree = $.fn.zTree.init($("#ztree"), settingss, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        })
        rMenu = $("#rMenu");
    });
    //显示6个，多余的省略
    function addDiyDom(treeId, treeNode) {
        var spaceWidth = 6;
        var switchObj = $("#" + treeNode.tId + "_switch"),
            icoObj = $("#" + treeNode.tId + "_ico");
        switchObj.remove();
        icoObj.parent().before(switchObj);
        var spantxt = $("#" + treeNode.tId + "_span").html();
        if (spantxt.length > 6) {
            spantxt = spantxt.substring(0, 6) + "...";
            $("#" + treeNode.tId + "_span").html(spantxt);
        }
    }

    //鼠标右键功能
    function onRightClick(event, treeId, treeNode) {
        if (treeNode && !treeNode.noR) {
            zTree.selectNode(treeNode);
            showRMenu("node", event.clientX, event.clientY);
        }
    }

    //修改前判断
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
            layer.msg("节点名称不能为空.");
            var zTree = $.fn.zTree.getZTreeObj("ztree");
            setTimeout(function () {
                zTree.editName(treeNode)
            }, 10);
            return false;
        }
        return true;
    }

    function showRMenu(type, x, y) {
        $("#rMenu ul").show();
        if (type == "root") {
            $("#m_del").hide();
        } else {
            $("#m_del").show();
        }

        y += document.body.scrollTop;
        x += document.body.scrollLeft;
        rMenu.css({"top": y + "px", "left": x + "px", "visibility": "visible"});
        $("body").bind("mousedown", onBodyMouseDown);
    }

    function hideRMenu() {
        if (rMenu) rMenu.css({"visibility": "hidden"});
        $("body").unbind("mousedown", onBodyMouseDown);
    }

    function onBodyMouseDown(event) {
        if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
            rMenu.css({"visibility": "hidden"});
        }
    }

    //添加节点
    addTreeNode = function addTreeNode() {
        hideRMenu();
        //获取节点信息
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: "添加课程",
            area: ['400px', '250px'],
            shade: 0.4,
            offset: 'auto',
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>课程分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='addNode' lay-verify='required' placeholder='请输入课程分类名称'>"
                + "</div></form>",
            btn: ['添加', '取消'],
            yes: function () {
                var title = $("#addNode").val();
                var courseClass = {
                    'parentId': categroyId,
                    'title': title,
                    'createId': createId,
                }
                $.ajax({
                    url: '/courseClass/addCourseClass',
                    type: 'post',
                    dataType: 'json',
                    data: courseClass,
                    success: function (data) {
                        if (data.data) {
                            layer.msg("添加成功");
                            location.reload();
                        } else {
                            layer.msg("添加失败");
                        }
                    }
                });
            }
        })
    }
    //删除节点
    removeTreeNode = function removeTreeNode() {
        hideRMenu();
        //获取节点信息
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.confirm("确认删除" + nodes[0].title + "课程分类?", {icon: 3, title: '提示'}, function (index) {
            if (nodes[0].isParent) {
                layer.msg("不能删除该目录，请从最底层目录开始删除!");
                return false;
            }
            $.ajax({
                url: '/courseClass/deleteCourseClass',
                type: 'post',
                data: {"categroyId": categroyId},
                dataType: 'json',
                success: function (data) {
                    if (data.data) {
                        layer.msg("删除成功");
                        location.reload();
                        return true;
                    } else {
                        layer.msg("删除失败");
                        return false;
                    }
                }
            });
        })
    }
    //修改节点
    edit = function edit() {
        hideRMenu();
        //获取节点信息
        var nodes = zTree.getSelectedNodes();
        var categroyId = nodes[0].categroyId;
        layer.open({
            type: 1,
            title: '修改课程分类',
            area: ['400px', '250px'],
            shade: 0,
            offset: 'auto',
            content: "<form class='layui-form'><div class='layui-form-item' style='margin: 20px;'>" +
                "<label class='layui-input-label'>课程分类：</label>"
                + "<input type='text' name='title' style='width:220px;height:30px;'id='updateNode' lay-verify='required' placeholder='请输入课程分类名称'>"
                + "</div></form>",
            btn: ['确定', '取消'],
            yes: function () {
                var title = $("#updateNode").val();
                var courseClass = {
                    'categroyId': categroyId,
                    'title': title,
                    'updateId': createId
                }
                if (title.length != 0) {
                    $.ajax({
                        url: '/courseClass/updateCourseClass',
                        type: 'post',
                        data: courseClass,
                        dataType: 'json',
                        success: function (data) {
                            if (data.data) {
                                layer.msg("修改成功");
                                document.location.reload();
                                return true;
                            } else {
                                layer.msg("修改失败");
                                return false;
                            }
                        }
                    });
                } else {
                    layer.msg("不能为空");
                }
            }
        });
    }


    //点击节点，展示对应类别下微圈信息
    function chooseNode(event, treeId, treeNode) {
        var classId = treeNode.categroyId;
        $.ajax({
            url: '/course/getCourse',
            type: 'post',
            dataType: 'json',
            data: {'classId': classId},
            success: function (data) {
                tablereload(data.data);
            }
        });
    }

    //加载表格数据
    getTable();

    function getTable() {
        $.ajax({
            url: '/course/getCourse',
            type: 'post',
            dataType: 'json',
            success: function (data) {
                tablereload(data.data);
            }
        });
    }

    var tableIns;

    //表格
    tablereload = function tablereload(data) {
        tableIns = table.render({
            elem: '#table',
            id: 'table',
            data: data,
            title: '课程列表',
            toolbar: '#toolbar',
            page: {
                limit: 10,
                layout: ['count', 'prev', 'page', 'next', 'skip', 'refresh'],
                first: '首页',
                last: '尾页'
            },
            cols: [
                [
                    {type: 'checkbox'},
                    {field: 'courseId', title: '课程编号', align: 'center'},
                    {
                        field: 'url', title: '课程图片', align: 'center', templet: function (data) {
                            return "<img src='http://" + data.url + "' style='width: 100px;height: 100px'>";
                        }
                    },
                    {field: 'courseName', title: '课程名称', align: 'center'},
                    {
                        field: 'courseNprice', title: '课程价格', align: 'center', templet: function (data) {
                            return "￥" + data.courseNprice;
                        }
                    },
                    {
                        field: 'courseStatus', title: '上架/下架', align: 'center', templet: function (data) {
                            if (data.courseStatus == 2) {
                                return '<a href="javascript:updateStaus(' + data.courseId + ',' + data.courseStatus + ');"><input class="layui-input" type="checkbox" name="switch" lay-skin="switch" lay-text="上架|下架" checked/></a>'
                            } else {
                                return '<a href="javascript:updateStaus(' + data.courseId + ',' + data.courseStatus + ');"><input class="layui-input" type="checkbox" name="switch" lay-skin="switch" lay-text="上架|下架"/></a>'
                            }
                        }
                    },
                    {field: 'title', title: '课程分类', align: 'center'},
                    {field: 'courseCstatus', title: '审核状态', align: 'center',templet:function (data) {
                            if (data.courseCstatus == 3){
                                return "<p>未审核</p>";
                            }else if (data.courseCstatus == 4){
                                return "<p>审核通过</p><a href='javascript:detailed(" + data.courseId + ");' style='color: #2F4056'>审核详细</a>";
                            } else if (data.courseCstatus == 5){
                                return "<p>审核中</p>";
                            }else {
                                return "<p>审核未通过</p><a href='javascript:detailed("+data.courseId+");' style='color: #2F4056'>审核详细</a>";
                            }
                        }},
                    {
                        field: '', title: '操作', align: 'center', templet: function (data) {
                            return "<div>" +
                                "<a href='javascript:getCourseById(" + data.courseId + ");' style='color: #2F4056;margin-right: 10px'>查看</a>" +
                                "<a href='javascript:updateCourse(" + data.courseId + ");' style='color: #2F4056'>编辑</a><br/>" +
                                "<a href='javascript:getjournal("+data.courseId+");' style='color: #2F4056; margin-right: 10px'>日志</a>" +
                                "<a href='javascript:deleteCourse(\"" + data.courseId + "\",\""+data.courseName+"\");' style='color: #2F4056'>删除</a>" +
                                "</div>";
                        }
                    }
                ]
            ],
        });
    }
    //修改课程的上架/下架
    updateStaus = function updateStaus(id,status){
        if (status==2){
            status = 3;
        }else {
            status = 2;
        }
        $.ajax({
            url:'/course/updatecourseStatus',
            type:'post',
            dataType:'json',
            data:{'courseId':id,'courseStatus':status,'updateId':createId},
            success:function (data) {
                if (data.data){
                    getTable();
                } else{
                    return false;
                }
            }
        });
    }
    //搜索
    form.on('submit(search)', function (data) {
        $.ajax({
            url: '/course/getCourse',
            type: 'post',
            data: data.field,
            dataType: 'json',
            success: function (data) {
                tablereload(data.data);
            }
        });
    })
    //重置
    $('#reset').click(function () {
        $('input[name=courseName]').val('');
        $('input[name=courseNprice]').val('');
        getTable();
    });
    //查看课程详细信息
    getCourseById = function getCourseById(id) {
        $.ajax({
            url:'/course/getCourseById',
            type:'post',
            dataType:'json',
            data:{'courseId':id,'userId':createId},
            success:function (data) {
                viewDetails(data.data);
            }
        });
    }
    function viewDetails(data){
        layer.open({
            type: 2,
            title: '查看课程详细信息',
            shade: 0,
            area: ['1000px', '500px'],
            offset: 't',
            maxmin: true,
            btn: ['关闭'],
            content: '/course/course-see.html',
            success: function (layero, index) {
                var obj = layero.find('iframe').contents();
                var url = "http://"+data.url;
                obj.find('#url').attr("src",url);
                var courseUrl = "http://"+data.courseUrl;
                obj.find('#courseUrl').attr("src",courseUrl);
                obj.find('input[name=courseName]').val(data.courseName);
                obj.find('input[name=createDate]').val(data.createDate);
                obj.find('input[name=trueName]').val(data.trueName);
                obj.find('input[name=courseNprice]').val(data.courseNprice);
                obj.find('input[name=coursePrimary]').val(data.coursePrimary);
                obj.find('input[name=title]').val(data.title);
                obj.find('input[name=likeNum]').val(data.likeNum);
                obj.find('input[name=collectNum]').val(data.collectNum);
                obj.find('input[name=commentNum]').val(data.commentNum);
                obj.find('#courseIntro').val(data.courseIntro);
            }
        });
    }
    //审核详细
    detailed = function detailed(courseId) {
        localStorage.setItem('courseId',courseId);
        layer.open({
            type: 2,
            title: '审核详细',
            area: ['700px', '400px'],
            content: '/course/course-audit-details.html',
            shade: 0,
            maxmin: true,
            offset: 't',
            btn:['关闭'],
            success:function (layero,index) {

            }
        });
    }
    //修改课程信息
    updateCourse = function updateCourse(courseId) {
        //查看信息
        $.ajax({
            url:'/course/getCourseById',
            type:'post',
            dataType:'json',
            data:{'courseId':courseId,'userId':createId},
            success:function (data) {
                updateviewDetails(data.data);
            }
        });
    }
    function updateviewDetails(data){
        localStorage.setItem("classId",data.classId);
        layer.open({
            type: 2,
            title: '修改课程详细信息',
            shade: 0,
            area: ['650px', '500px'],
            offset: 't',
            maxmin: true,
            content: '/course/course-update.html',
            success: function (layero, index) {
                var obj = layero.find('iframe').contents();
                var url = "http://"+data.url;
                obj.find('#url').attr("src",url);
                obj.find('input[name=url]').val(data.url);
                var courseUrl = "http://"+data.courseUrl;
                obj.find('#courseUrl').attr("src",courseUrl);
                obj.find('input[name=courseUrl]').val(data.courseUrl);
                obj.find('input[name=courseTime]').val(data.courseTime);
                obj.find('input[name=courseName]').val(data.courseName);
                obj.find('input[name=createDate]').val(data.createDate);
                obj.find('input[name=trueName]').val(data.trueName);
                obj.find('input[name=courseNprice]').val(data.courseNprice);
                obj.find('input[name=coursePrice]').val(data.coursePrice);
                obj.find('input[name=coursePrimary]').val(data.coursePrimary);
                obj.find('#courseIntro').val(data.courseIntro);
                obj.find('input[name=courseId]').val(data.courseId);
                obj.find('input[name=userId]').val(data.userId);
                obj.find('input[name=courseStatus]').val(data.courseStatus);
                obj.find('input[name=courseCstatus]').val(data.courseCstatus);
            }
        });
    }
    //日志
    getjournal = function getjournal(courseId) {
        localStorage.setItem('journalCourseId',courseId);
        layer.open({
            type: 2,
            title: '日志详细',
            area: ['700px', '400px'],
            content: '/course/course-journal.html',
            shade: 0,
            maxmin: true,
            offset: 't',
            btn:['关闭'],
            success:function (layero,index) {

            }
        });
    }
    //删除课程
    deleteCourse = function deleteCourse(courseId,courseName) {
        layer.confirm('是否删除' + courseName + '课程', {
            icon: 3, title: '提示'
        }, function (index) {
            //获取使用人id
            var createId = $('input[name=createId]').val();
            $.ajax({
                url: '/course/deleteCourse',
                type: 'post',
                dataType: 'json',
                data: {'courseId': courseId, 'userId': createId},
                success: function (data) {
                    if (data.data) {
                        //删除审核记录中的数据
                        $.ajax({
                            url: '/record/deleteRecord',
                            type: 'post',
                            dataType: 'json',
                            data: {'courseId': courseId, 'type': 2},
                            success: function (data) {
                                if (data.data) {
                                    layer.msg("删除成功");
                                    getTable();
                                } else {
                                    layer.msg("删除失败")
                                }
                            }
                        });
                    } else {
                        layer.msg("删除失败")
                    }
                }
            });
        })
    }
    //高级检索
    $('#retrieval').on('click',function () {
        layer.open({
            type: 2,
            title: '高级检索',
            area: ['700px', '350px'],
            content: '/course/course-advanced-retrieval.html',
            shade: 0,
            maxmin: true,
            offset: 't',
            success:function (layero,index) {

            }
        });
    })
    //添加
    table.on('toolbar(test)',function (obj) {
        switch (obj.event) {
            case 'importCourse':
                layer.open({
                    type:1,
                    title:'课程导入',
                    offset:'auto',
                    shade:0.5,
                    content:$('#Drag'),
                    success:function (layero,index) {
                        upload.render({
                            elem:'#Drag',
                            url:'/course/importExcel',
                            accept:'file',
                            method: 'post',
                            type:'file',
                            field:'file',
                            drag:true,
                            acceptMime:'.xlsx,.xls',
                            exts:'xls|xlsx',
                            done:function (res,index,upload) {
                                if (res.data == '无数据') {
                                    layer.msg("无数据导入");
                                    location.reload();
                                    return;
                                }
                                if (res.code == 0){
                                    layer.msg("导入成功");
                                    location.reload();
                                }else {
                                    layer.msg("导入失败");
                                }
                            }
                        });
                    }
                });
                break;
        }
    });
    //返回
    goBack = function goBack() {
        parent.$('#Jump').val('首页');
        parent.getQuick();
        return;
    }
})
